package com.xpc.rpc.codec;

import com.xpc.rpc.common.enums.SerializationType;
import com.xpc.rpc.common.serialization.Serialization;
import com.xpc.rpc.protocol.ProtocolMessage;
import com.xpc.rpc.serialization.jdk.JdkSerialization;
import com.xpc.rpc.spi.loader.ExtensionLoader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;


public class RpcEncoder extends MessageToByteEncoder<ProtocolMessage> implements RpcCoder {


    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, ProtocolMessage protocolMessage, ByteBuf out) throws Exception {
        out.writeInt(protocolMessage.getRpcHeader().getMsgType());
        String serializationValue = SerializationType.getVal(protocolMessage.getRpcHeader().getSerializationType());
        //获取序列化接口
        Serialization serialization = ExtensionLoader.getExtension(Serialization.class, serializationValue);
        byte[] bytes = serialization.serialize(protocolMessage.getT());
        out.writeInt(bytes.length);
        out.writeLong(protocolMessage.getRpcHeader().getRequestId());
        out.writeInt(protocolMessage.getRpcHeader().getSerializationType());
        out.writeBytes(bytes);
    }
}
